<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区 -->
    <el-card>
      <el-row :gutter="30">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-table :data="userlist" border stripe>
        <!-- //索引项 -->
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- v-slot="scope" -->
            <!-- {{scope.row}} 该条数据的所有信息 -->
            <!-- 插入开关作用域插槽 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStatesChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- slot-scope="scope"定义属性插入具名插槽 -->
            <!-- 修改信息 -->
            <el-tooltip effect="dark" content="编辑信息" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showEdiDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 更改角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-star-off"
                @click="editrolesInfo(scope.row)"
              ></el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <!-- 添加的内容区域
      rules 验证规则-->
      <el-form :model="addForm" :rules="addFrormRules" ref="addFormRef" label-width="60px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加的底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户弹出框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 修改的内容区域
      rules 验证规则-->
      <el-form :model="editForm" :rules="editFrormRules" ref="editFormRef" label-width="60px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 修改的底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- //分配角色弹出框 -->
    <el-dialog title="修改用户" :visible.sync="editrolesVisible" width="50%">
      <!-- 修改角色的内容区域 -->
      <el-form :model="editRulesForm" ref="editRulesFormRef" label-width="60px">
        <p>当前的用户: {{editRulesForm.username}}</p>
        <p>当前的角色: {{editRulesForm.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="getRoleId" placeholder="请选择">
            <el-option
              v-for="item in getRoles"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </el-form>
      <!-- 修改的底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editrolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole(editRulesForm.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { log } from 'util'
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cd) => {
      const regEmail = /^[0-9a-zA-Z_.-]+@[0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/

      if (regEmail.test(value)) {
        //合法邮箱
        return cd()
      }
      cd(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cd) => {
      const regMobile = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/

      if (regMobile.test(value)) {
        //合法手机号
        return cd()
      }
      cd(new Error('请输入合法的手机号'))
    }
    return {
      //获取用户列表参数对象
      queryInfo: {
        query: '',
        //当前页码
        pagenum: 1,
        // 每页多少条数据
        pagesize: 3
      },
      userlist: [],
      total: 0,

      //控制添加用户框的弹出
      dialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //添加表单的用户验证规则
      addFrormRules: {
        username: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //控制修改用户弹出框
      editDialogVisible: false,
      //由id获取到的数据对象
      editForm: {},
      //修改信息的验证规则
      editFrormRules: {
        email: [
          { required: true, message: '请输入合法邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入合法手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //控制修改角色框的弹出
      editrolesVisible: false,

      //当前被分配角色的用户信息
      editRulesForm: {},
      //获取所有角色列表
      getRoles: [],
      //已选中的角色id
      getRoleId: ''
    }
  },
  //生命周期函数
  created() {
    // 得到并加载当前数据和方法
    // this.
    this.getUserList()
  },
  methods: {
    // getUserList() {
    //   // 发送get请求 params携带请求时的参数
    //   this.$http.get('users', { params: this.queryInfo })
    // )
    //   //返回promise对象 我们可以简写成
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status != 200) return this.$mwssage.error('获取用户列表失败')
      this.userlist = res.data.users
      this.total = res.data.total
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      // 改变之后在重新加载数据
      this.getUserList()
    },
    //监听页码值的改变
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      // 改变之后在重新加载数据
      this.getUserList()
    },
    //监听用户状态值
    async userStatesChanged(userinfo) {
      // console.log(userinfo)
      //发送put请求修改用户状态
      // console.log(userinfo.id)
      // console.log(userinfo.mg_state)

      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      console.log(res)

      console.log(res.meta.status)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('修改用户状态失败')
        //失败之后要恢复之前状态
      }
      this.$message.success('修改用户状态成功')
    },
    // 添加对话框关闭之后，重置表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //点击按钮,添加新用户
    addUser() {
      //先验证信息是否符合规则
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 符合规则后发起请求数据库,添加用户信息
        const { data: res } = await this.$http.post('/users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功!')
        //并且关闭添加用户框
        this.dialogVisible = false
        //数据发生改变,需要从新加载渲染用户列表数据
        this.getUserList()
      })
    },
    // 点击按钮编辑修改用户信息
    async showEdiDialog(id) {
      this.editDialogVisible = true
      console.log(id)
      //根据获取过来的id 发送请求获得用户数据 该数据是个promise值 要用 axync await
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)

      if (res.meta.status !== 200)
        return this.$message.error('获取用户信息失败')
      // //获取成功后赋值到修改列表数据
      this.editForm = res.data
    },
    // 编辑对话框关闭之后，重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      //先验证
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 符合规则后发起请求数据库,修改用户信息
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        console.log(res)
        console.log(res.meta.status)

        if (res.meta.status !== 200)
          return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功!')
        //并且关闭添加用户框
        this.editDialogVisible = false
        //数据发生改变,需要从新加载渲染用户列表数据
        this.getUserList()
      })
    },
    // 点击删除该id用户
    async removeUserById(id) {
      console.log(id)
      // 弹框提示是否删除
      const confiemResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(res => res)
      //表示按下取消按钮输出
      //cancel 取消

      // 删除确认输出
      console.log(confiemResult) //confirm删除
      //取消删除
      if (confiemResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      //确认删除后,发送数据请求
      const { data: res } = await this.$http.delete('users/' + id)
      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('删除用户信息失败')
      this.$message.success('删除用户信息成功!')
      //并且关闭删除用户框
      // this.editDialogVisible = false
      //数据发生改变,需要从新加载渲染用户列表数据
      this.getUserList()
    },
    //点击修改用户角色
    async editrolesInfo(roleUser) {
      this.editRulesForm = roleUser
      console.log(roleUser)
      //获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      this.getRoles = res.data
      console.log(this.getRoles)

      this.editrolesVisible = true
    },
    // 点击确认修改角色信息
    async editRole(uid) {
      const { data: res } = await this.$http.put('users/' + uid + '/role', {
        rid: this.getRoleId
      })
      console.log(this.getRoleId)

      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('修改用户角色失败')
      this.$message.success('修改用户角色成功')
      //加载数据
      this.getUserList()
      // 关闭修改角色框
      this.editrolesVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-pagination {
  margin-top: 15px;
}
</style>>
